from django.shortcuts import render
from django.views import View

# 导入序列化器
from .serializers import *
from iClouds.apidev import redis_key_set, redis_list_append
from PlaceManager.tasks import has_pid_from_idcode

import random


# Create your views here.
class hello(View):
    def get(self, request):
        return HttpResponse("GET 方法")

    def post(self, request):
        return HttpResponse("POST 方法")


class AllinpayHardwareListSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所硬件列表或详情"
    __group__ = "场所资产"
    __info__ = {"get": "查询场所终端列表或详情"}
    __doc__ = """
    list:\n
    <h4>场所硬件列表</h4>
    retrieve:\n
    <h4>场所硬件详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [
        MyJWTAuthentication,
        BoxJWTAuthentication,
        WeChatJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [
        MyPermissions | BoxPermissions | WeChatPermissions | BarPermissions
    ]
    serializer_class = AllinpayHardwareListSerializer
    queryset = AllinpayHardwareList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "pcname", "mac", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayHardwareConfSetViewSet(viewsets.ModelViewSet):
    __title__ = "场所硬件配置"
    __group__ = "场所资产"
    __info__ = {"get": "查询场所硬件配置列表或详情", "patch": "编辑场所硬件配置"}
    __doc__ = """
    list:\n
    <h4>场所硬件配置列表</h4>
    retrieve:\n
    <h4>场所硬件配置详情</h4>
        name=(
            ("area", "区域变更报警"),
            ("ipaddr", "ip地址变更报警"),
            ("mac", "MAC变更报警"),
            ("board", "主板变更报警"),
            ("cpu", "CPU变更报警"),
            ("memory", "内存变更报警"),
            ("video", "显卡变更报警"),
            ("display", "显示器变更报警"),
            ("netadapter", "网卡变更报警"),
            ("network", "网络连接变更报警"),
            ("mouse", "鼠标变更报警"),
            ("keyboard", "键盘变更报警"),
            ("headset", "音频设备变更报警"),
            ("cpu_temperature", "CPU温度阈值报警"),
            ("board_temperature", "主板温度阈值报警"),
            ("video_temperature", "显卡温度阈值报警"),
            ("speed", "网卡速率阈值报警"),

        compare=(
            ("equal", "变更(不等于原值)"),
            ("exact", "等于"),
            ("gt", "大于"),
            ("gte", "大于等于"),
            ("lt", "小于"),
            ("lte", "小于等于"),
            ("ne", "不等于"),
            ("contains", "包含"),
            ("isnull", "是否为null"),
            ("equal", "字符串变更"),
        )

        示例:
        max  exact  1
        cpu_temperature gt 90
        speed lt 1000
    partial_update:\n
    <h4>编辑场所硬件配置</h4>
    """
    http_method_names = ["get", "patch"]
    authentication_classes = [MyJWTAuthentication, BoxJWTAuthentication]
    permission_classes = [MyPermissions | BoxPermissions]
    serializer_class = AllinpayHardwareConfSerializer
    queryset = AllinpayHardwareConf.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "name"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(pid=request.user.id)
        # 异步消息
        # SendAsyncMessage(
        #     serializer.data.get("pid"),
        #     "AllinpayHardwareConf",
        #     f'/hard/conf/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        if request.data.get("name"):
            raise serializers.ValidationError({"name": "该字段禁止编辑"})
        if request.data.get("pid"):
            raise serializers.ValidationError({"pid": "该字段禁止编辑"})
        instance = self.get_object()
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 异步消息
        # SendAsyncMessage(
        #     instance.pid,
        #     "AllinpayHardwareConf",
        #     f"/hard/conf/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class PlaceWorkStationListViewSet(viewsets.ModelViewSet):
    __title__ = "工作站列表"
    __group__ = "场所资产"
    __info__ = {"get": "工作站列表查询"}
    __doc__ = """	list:
    <h4>工作站列表列表</h4>
    retrieve:
    <h4>详情</h4>
    create:
    <h4>创建</h4>
    update:
    <h4>编辑</h4>
    delete:
    <h4>移除</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ['pid', 'intetype']
    def toName(self, hao):
        x = str(hao)
        if len(x) == 1:
            return f"00{x}"
        elif len(x) == 2:
            return f"0{x}"
        else:
            return f"{x}"

    def list(self, request, *args, **kwargs):
        # queryset = self.filter_queryset(self.get_queryset())
        # serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": ""})

    def retrieve(self, request, *args, **kwargs):
        # print(args, kwargs)
        pk = kwargs.get("pk")

        # instance = self.get_object()
        # serializer = self.get_serializer(instance)
        works = []
        for i in range(1, 136):
            works.append(
                {
                    "hostname": self.toName(i),
                    "ipaddr": "192.168.0.73",
                    "mac": "ff:ff:ff:ff:ff:ff",
                    "status": random.choice(range(4)),
                    "name": "谭*伟",
                    "gender": random.choice(range(2)),
                    "level": random.choice(["青铜会员", "白银会员", "黄金会员", "铂金会员", "钻石会员"]),
                    "online": "2023-05-25 12:00:00",
                    "love": random.choice(range(100)),
                    "hong": random.choice(range(100)),
                    "friend": random.choice(range(100)),
                }
            )
        data = {"codeid": pk, "works": works}
        return Response({"rescode": 200, "resmsg": data})


# from . import testPublic, testAPublic

# testPublic.out("ceshi 静态类")
# testAPublic().out("ceshi 动态类")


class FsygWorkLoginViewSet(viewsets.ModelViewSet):
    __title__ = "场所终端登录"
    __group__ = "场所终端"
    __info__ = {"post": "场所终端登录"}
    __doc__ = """
    create:
    <h4>场所终端登录</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = FsygWorkLoginSerializer
    queryset = FsygLineinfoList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 初始化数据
        data = serializer.data.copy()
        pid = has_pid_from_idcode("凡商编码", data.get("wbid"))
        if not pid:raise serializers.ValidationError("查询门店失败")            
        try:
            r = FsygLineinfoList.objects.get(**data)
            p = AllinpayPlaceList.objects.get(id=pid, status=1)
            w = FsygPchardList.objects.get(pid=p.id, name=data.get("computer_name"))
            g = w.group
        except FsygLineinfoList.DoesNotExist as err:
            raise serializers.ValidationError("查询在线数据失败")
        except AllinpayPlaceList.DoesNotExist as err:
            g = ""
        except FsygPchardList.DoesNotExist as err:
            g = ""
        except BaseException as err:
            raise serializers.ValidationError("查询失败")
        else:
            res = FsygLineinfoListSerializer(r).data
            res["group"] = g
        return Response({"rescode": 200, "resmsg": res})


# 检查视图
filter_views(globals())
